package com.duan.config;

import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author db
 * @version 1.0
 * @description ControllerResponseAdvice
 * @since 2024/1/3
 *
 * 使用ResponseBodyAdvice对Controller的所有返回值进行封装
 */
@ControllerAdvice
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body != null) {
            try {
                HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
                servletRequest.setAttribute("responseParams", JSON.toJSONString(body));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return body;
    }
}
